package Controllers;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import Boundry.ApproveDenyExtenstionGUI;
import Boundry.CloseRequestPanel;
import Boundry.InitTaskPanel;
import Boundry.InspectorApprovalReqPanel;
import Boundry.SuspendRequestPanel;
import Boundry.ViewReuestDataPanel;
import Boundry.ViewReuestsTablePanel;
import Boundry.Waiting;
import Boundry.GenericTools.RequestTableListPanel;
import Controllers.GenericToolsForController.BaseClass;
import Controllers.GenericToolsForController.PDFDocument;
import Controllers.GenericToolsForController.PDFfile;
import Controllers.GenericToolsForController.RequestMainStatusEnum;
import Controllers.GenericToolsForController.RequestStepStatusEnum;
import Controllers.GenericToolsForController.WorkerPostion;
import Controllers.GenericToolsForController.WorkerRolls;
import Entity.Request;
import Entity.RequestStatusHistory;
import Entity.Status;
import Entity.User;
import Entity.Worker;

public class InspectorController extends BaseClass
{
	private RequestTableListPanel closeRequestTableListPanel;  //for Closing Step
	private CloseRequestPanel closeRequestPanel;
	
	
	private RequestTableListPanel suspendRequestTableListPanel; 	//for suspending Step
	private SuspendRequestPanel suspendRequestPanel;
	
	
	private RequestTableListPanel initRequestTableListPanel;  //  for  init task step
	private InitTaskPanel initTaskPanel;
	
	private ViewReuestsTablePanel viewReuestsTablePanel;
	private ViewReuestDataPanel viewReuestDataPanel;
	private int closeReqTab=0,openReqTab=1,suspendReqTab=2;
	
	
	private InspectorApprovalReqPanel inspectorApprovalReqPanel;
	private int TimeToSepTab=1,ExetendedTab=0;
	
	private List<Request> requestToChoose;
	
	private RequestTableListPanel TimeExtensionRequestTableListPanel ; //for Time Extension step
	private ApproveDenyExtenstionGUI aproovedeny;
	private List<Request> requestToInit;
	private List<Request> requestCloselist;
	private List<Request> requestOpenlist ;
	private List<Request> requestSuspendedlist;
	private List<Request> requestExetendedList ;
	private List<Request> requestTimeToSep;
	
	
	private Request chosenReq;
	private Waiting waitScreen;
	/*
	 * Singleton 
	 */
	private static  InspectorController Instance = null;
	private InspectorController(){}
	public static InspectorController getInstance()
	{
		if(Instance == null)
		{
			Instance = new InspectorController();
		}
		return Instance;
	}
	
	/**
	 * 
	 * 
	 * closeRequest method stands for building the gui panel for viewing the close requests for the current worker
	 * 
	 * 
	 * 
	 */
	
	// Operation
	public void closeRequest()
	{	
		
		waitScreen = new Waiting();
		SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
		@Override
		 public Void doInBackground() 
		 {
			//System.out.println("");
			System.out.println(" RequestManager.getInstance().getAllRequestToCloseRequest() ");
			
			requestToChoose = RequestManager.getInstance().getAllRequestToCloseRequest(0);
			
			if(requestToChoose.size() <= 0)
			{
				waitScreen.kill();
				JOptionPane.showMessageDialog(new JFrame(),"There Is Not Request That Can Be Close", "",JOptionPane.DEFAULT_OPTION);
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else
			{
				closeRequestTableListPanel = new RequestTableListPanel();
				
				GlobalData.guiMangaer.switchScreen(closeRequestTableListPanel);
				
				tableData =  new String[requestToChoose.size()][requestToChoose.get(0).dataToStringArray().length];
				for(int i=0; i<tableData.length ; i++)
				{
					tableData[i] = requestToChoose.get(i).dataToStringArray();
				}
				columnNames = requestToChoose.get(0).indexStringArray();

				closeRequestTableListPanel.buildTabel(columnNames,tableData);
				setListenerToViewDataPanel(closeRequestTableListPanel);
			}
			return null;
		}
		@Override
		public void done() 
		{
			waitScreen.kill();
			waitScreen=null;
		}
	    };  
		worker.execute();
	}
	/**
	 * 
	 * suspendRequest method stands for building the gui panel for viewing the suspend Requests for the current worker
	 * 
	 */
	public void suspendRequest()
	{
		waitScreen = new Waiting();
		SwingWorker worker = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {				
					
				requestToChoose = RequestManager.getInstance().getAllRequestThatCanBeSuspend();
				
				//Build table for the Suspended request list.
				if(requestToChoose.size()>0)
				{
					tableData =  new String[requestToChoose.size()][requestToChoose.get(0).dataToStringArray().length];
					for(int i=0; i<tableData.length ; i++)
					{
						tableData[i] = requestToChoose.get(i).dataToStringArray();
					}
					columnNames = requestToChoose.get(0).indexStringArray();

					suspendRequestTableListPanel = new RequestTableListPanel();
					GlobalData.guiMangaer.switchScreen(suspendRequestTableListPanel);
					suspendRequestTableListPanel.buildTabel(columnNames,tableData);
					setListenerToViewDataPanel(suspendRequestTableListPanel);	
				}
				else
				{
					waitScreen.kill();
					JOptionPane.showMessageDialog(new JFrame(),"There is not request that can be suspended", "",JOptionPane.DEFAULT_OPTION);
				}
				return null;
			}
			@Override
			public void done() 
			{
				waitScreen.kill();
				waitScreen = null;
			}
		    };  
			worker.execute();

	}
	/**
	 * 
	 *initTask -method stands for building the gui panel for viewing the Requests for initTask the current worker
	 * 
	 * 
	 */
	public void initTask()
	{

		 requestToInit = RequestManager.getInstance().getAllUnassignedRequest(GlobalData.worker.getId(),WorkerPostion.INSPECTOR);
		 
		if (requestToInit.size()==0)
		{
			JOptionPane.showMessageDialog(new JFrame(),"There are no new requests to intilize", "",JOptionPane.DEFAULT_OPTION);
			return;
		}
		/*
		 * construct the table by the relevant fields
		 * 
		 */
		System.out.println("InitTASK OK!");
		String[] columnNames = { "Request Id", "Field1", "Field2 ", "Field3" };
		String[][] tableData = {{}};
		
		tableData =  new String[requestToInit.size()][requestToInit.get(0).dataToStringArray().length];

		for(int i=0; i<tableData.length ; i++)
		{
			tableData[i] = requestToInit.get(i).dataToStringArray();
		}
		columnNames = requestToInit.get(0).indexStringArray();

		initRequestTableListPanel = new RequestTableListPanel();
		GlobalData.guiMangaer.switchScreen(initRequestTableListPanel);
		initRequestTableListPanel.buildTabel(columnNames,tableData);
		setListenerToViewDataPanel(initRequestTableListPanel);	
		
	}
	
	
	
	
	public void showAllRequests() 
	{
		waitScreen = new Waiting();
		SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {				
				System.out.println("  Get All Request : Close,Open,Suspend By Inspector ");
				
				requestCloselist  = RequestManager.getInstance().getAllCloseRequestsByInspector();
				requestOpenlist = RequestManager.getInstance().getAllOpenRequestsByInspector();
				requestSuspendedlist = RequestManager.getInstance().getAllSuspendedRequestsByInspector();

				System.out.println("requestSuspendedlist:" + requestSuspendedlist.size() + "requestOpenlist: " +	requestOpenlist.size()
						+ "requestCloselist : " + requestCloselist.size()
						);
				//Build table for the Suspended request list.
				if( requestCloselist==null && requestOpenlist==null && requestSuspendedlist==null)			 
				{
					waitScreen.kill();
					JOptionPane.showMessageDialog(new JFrame(),"There is not request for Inspector", "",JOptionPane.DEFAULT_OPTION);
				}
				else
				{
					try 
					{
						viewReuestsTablePanel =  new ViewReuestsTablePanel(3);
						viewReuestsTablePanel.buildTabPanel();
						GlobalData.guiMangaer.switchScreen(viewReuestsTablePanel);
					} 
					catch (Exception e) 
					{
						e.printStackTrace();
					}
									
					try {
						
						//Close Req
						if(requestCloselist!=null && requestCloselist.size()>0)
						{
							tableData =  new String[requestCloselist.size()][requestCloselist.get(0).dataToStringArray().length];
							for(int i=0; i<tableData.length ; i++)
							{
								tableData[i] = requestCloselist.get(i).dataToStringArray();
							}
							columnNames = requestCloselist.get(0).indexStringArray();
							System.out.println("There is request Close list " + requestCloselist.size() );
							viewReuestsTablePanel.buildTabI(closeReqTab,"Closed Requests","Close Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									columnNames,tableData);
						}
						else
						{
							viewReuestsTablePanel.buildTabI(closeReqTab,"Closed Requests","Close Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									null,null);
							System.out.println("There is not requestCloselist");
						}
						
						
						
						// Open Req
						if(requestOpenlist!=null && requestOpenlist.size()>0)
						{
							tableData =  new String[requestOpenlist.size()][requestOpenlist.get(0).dataToStringArray().length];
							for(int i=0; i<tableData.length ; i++)
							{
								tableData[i] = requestOpenlist.get(i).dataToStringArray();
							}
							columnNames = requestOpenlist.get(0).indexStringArray();
							
							System.out.println("There is openReq " + requestOpenlist.size() );
							
							viewReuestsTablePanel.buildTabI(openReqTab,"Open Requests","Open Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									columnNames,tableData);
						}
						else
						{
							viewReuestsTablePanel.buildTabI(openReqTab,"Open Requests","Open Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									null,null);
							System.out.println("There is not openReqTab");
						}
						
						
						
						//suspend ReqrequestOpenlist
						if(requestSuspendedlist!=null && requestSuspendedlist.size()>0)
						{
							tableData =  new String[requestSuspendedlist.size()][requestSuspendedlist.get(0).dataToStringArray().length];
							for(int i=0; i<tableData.length ; i++)
							{
								tableData[i] = requestSuspendedlist.get(i).dataToStringArray();
							}
							columnNames = requestSuspendedlist.get(0).indexStringArray();
							System.out.println("There is request Suspended list " + requestSuspendedlist.size() );
							viewReuestsTablePanel.buildTabI(suspendReqTab,"Suspend Requests","Suspend Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									columnNames,tableData);
						}
						else
						{
							viewReuestsTablePanel.buildTabI(suspendReqTab,"Suspend Requests","Suspend Requests List for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									null,null);
							System.out.println("There is not suspendReqTab");
						}
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
	
					setListenerToViewDataPanel(viewReuestsTablePanel);	
				}
				return null;
			}
			@Override
			public void done() 
			{
				waitScreen.kill();
				waitScreen = null;
			}
		    };  
			worker.execute();
		
	}
	
	public void InspectorApproval() 
	{
		waitScreen = new Waiting();
		//inspectorApprovalReqPanel
		SwingWorker worker = new SwingWorker<Void, Void>() {
			@Override
			 public Void doInBackground() 
			 {				
				System.out.println("  InspectorApproval Starts ");
				/*
				 * need to Approve:
				 *  - Time to Extension
				 *  - Time to Step
				 */
				requestExetendedList = RequestManager.getInstance().getAllRequestsThatNeedExtantionByInspector();
				requestTimeToSep = RequestManager.getInstance().getAllRequestsThatNeedTimeSepApproval();

				System.out.println("requestExetendedList:" + requestExetendedList.size() + "requestTimeToSep: " +	requestTimeToSep.size());
				//Build table for the Suspended request list.
				if( requestExetendedList==null && requestTimeToSep==null )
				{
					waitScreen.kill();
					JOptionPane.showMessageDialog(new JFrame(),"There is not request for Inspector", "",JOptionPane.DEFAULT_OPTION);
				}
				else
				{
					try 
					{
						inspectorApprovalReqPanel =  new InspectorApprovalReqPanel(2);
						GlobalData.guiMangaer.switchScreen(inspectorApprovalReqPanel);
					} 
					catch (Exception e) 
					{
						e.printStackTrace();
					}
									
					try
					{
						//Time Extention Req
						if(requestExetendedList!=null && requestExetendedList.size()>0)
						{
							tableData =  new String[requestExetendedList.size()][requestExetendedList.get(0).dataToStringArray().length];
							for(int i=0; i<tableData.length ; i++)
							{
								tableData[i] = requestExetendedList.get(i).dataToStringArray();
							}
							columnNames = requestExetendedList.get(0).indexStringArray();
							System.out.println("There is requestExetendedList  " + requestExetendedList.size() );
							inspectorApprovalReqPanel.buildTabI(ExetendedTab,"Time Extention","Requests List that need time extention for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									columnNames,tableData);
						}
						else
						{
							inspectorApprovalReqPanel.buildTabI(ExetendedTab,"Time Extention","Requests List that need time extention for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									null,null);
							System.out.println("There is not requestExetendedList");
						}
						
						
						// Open Req
						if(requestTimeToSep!=null && requestTimeToSep.size()>0)
						{
							tableData =  new String[requestTimeToSep.size()][requestTimeToSep.get(0).dataToStringArray().length];
							for(int i=0; i<tableData.length ; i++)
							{
								tableData[i] = requestTimeToSep.get(i).dataToStringArray();
							}
							columnNames = requestTimeToSep.get(0).indexStringArray();
							
							System.out.println("There is openReq " + requestTimeToSep.size() );
							
							inspectorApprovalReqPanel.buildTabI(TimeToSepTab,"Time For Step","Requests List Of time to Step for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									columnNames,tableData);
						}
						else
						{
							inspectorApprovalReqPanel.buildTabI(TimeToSepTab,"Time For Step","Requests List Of time to Step for the inspector " + GlobalData.worker.getFirstName() + " " + GlobalData.worker.getLastName(),
									null,null);
							System.out.println("There is not openReqTab");
						}
						inspectorAprovalListner();	
						
					}
					catch (Exception e) 
					{
						e.printStackTrace();
					}
						
					}
						
				return null;
			}
			/**
			 * 
			 */

			@Override
			public void done() 
			{
				waitScreen.kill();
				waitScreen = null;
			}
		    };  
			worker.execute();
		
	}
	
	
	private void inspectorAprovalListner() 
	{
		setListenerToViewDataPanel(inspectorApprovalReqPanel);					
		inspectorApprovalReqPanel.getBtnDeny().addActionListener(this);
		inspectorApprovalReqPanel.getBtnApprove().addActionListener(this);
		 inspectorApprovalReqPanel.getCellSelectionModel(TimeToSepTab).addListSelectionListener(new ListSelectionListener() 
		    {
				@Override
				public void valueChanged(ListSelectionEvent arg0) 
				{
					setDateToinspectorApprovalReqPanel();	
					
				}

				
			  });
		inspectorApprovalReqPanel.getCellSelectionModel(ExetendedTab).addListSelectionListener(new ListSelectionListener() 
	    {
			@Override
			public void valueChanged(ListSelectionEvent arg0) 
			{
				setDateToinspectorApprovalReqPanel();
			}
		  });
	}
	/**
	 * 
	 */
	private void setDateToinspectorApprovalReqPanel()
	{
		int i = inspectorApprovalReqPanel.getChosen();
		if(i<0) return;
		int tab = inspectorApprovalReqPanel.getChooseTab();
		if(tab==TimeToSepTab)
		{
			System.out.println("i  = " + i);
			chosenReq = requestTimeToSep.get(i);
		}
		else if(tab==ExetendedTab)
		{
			chosenReq = requestExetendedList.get(i);
		}
		String step =null;
		if(chosenReq.isInEvluation())
		{
			step = "Evluation" ; 
		}
		else if(chosenReq.isInExecuation())
		{
			step = "Execuation" ; 
		}
		else if(chosenReq.isInReviewAndDecision())
		{
			step = "Review And Decision" ; 
		}
		else if(chosenReq.isInTesting())
		{
			step = "Testing" ; 
		}
		int days =(int) ( chosenReq.getCurrentStatus().getDueDate().getTime() - chosenReq.getCurrentStatus().getStartDate().getTime() )/(1000*60*60*24);
		inspectorApprovalReqPanel.setReason(chosenReq.getCurrentStatus().getComment());
		inspectorApprovalReqPanel.setInitator(chosenReq.getInitiator().getFirstName() +" "+ chosenReq.getInitiator().getLastName());
		inspectorApprovalReqPanel.setDateOfCreation(chosenReq.getDate().toString());
		inspectorApprovalReqPanel.setIntoSystem(chosenReq.getInfoSystem().getName());
		inspectorApprovalReqPanel.setCurrentStep(step);
		inspectorApprovalReqPanel.setDays("" +days );
	}
	
	public void editRequest()
	{
		//TODO to be implemented
		System.out.println("editRequest is not implemented  ");	
	}
	
	public void showAllClosedRequests()
	{
		//TODO to be implemented
		System.out.println("showAllClosedRequests is not implemented  ");	
	}
	
	
	public void clearFieldsinspectorApprovalReqPanel()
	{
		inspectorApprovalReqPanel.setReason("");
		inspectorApprovalReqPanel.setInitator("");
		inspectorApprovalReqPanel.setDateOfCreation("");
		inspectorApprovalReqPanel.setIntoSystem("");
		inspectorApprovalReqPanel.setCurrentStep("");
		inspectorApprovalReqPanel.setDays("" );
		inspectorApprovalReqPanel.setInspectorExplanation("");
	}
	
	
	
	
	
	
	@SuppressWarnings("deprecation")
	@Override
	public void actionPerformed(ActionEvent e) 
	{	
		initTaskListener(e);
		/*
		 * close Request Handle Listener
		 */
		closeRequestListener(e);
		/*
		 * suspend Request Handle Listener
		 */
		suspendRequestListner(e);
		/*
		 * Init Task
		 */
		approveOrDenyTimeExtensionRequestListener(e);
		
		viewReuestsTableListener(e);
		
		inspectorApprovalReqListener(e);
	}
	
	
	private void inspectorApprovalReqListener(ActionEvent e)
	{
		if(inspectorApprovalReqPanel!=null)
		{
			if (e.getSource() == inspectorApprovalReqPanel.btnNext)
			{
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == inspectorApprovalReqPanel.btnBack)
			{
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == inspectorApprovalReqPanel.btnRefresh)
			{	
				InspectorApproval() ;
			}
			else if (e.getSource() == inspectorApprovalReqPanel.getBtnApprove())
			{
				if(inspectorApprovalReqPanel.getChosen()<0)
				{
					JOptionPane.showMessageDialog(new JFrame(),"Please select request from the request list.","Error",JOptionPane.ERROR_MESSAGE);
					return;
				}
				if(inspectorApprovalReqPanel.getChooseTab() == TimeToSepTab )
				{
	
					Status newStatus;
					RequestStepStatusEnum step=null;
					Status current = chosenReq.getCurrentStatus().getStatus();
					if(chosenReq.isInEvluation())
					{
						if(current.getsStatus() == RequestStepStatusEnum.EVL_UNVALUATED_WITH_TIME_PENDING)
							step = RequestStepStatusEnum.EVL_UNVALUATED_WITH_TIME;
						else if(current.getsStatus() == RequestStepStatusEnum.EVL_REAVLAUTION_WITH_TIME_PENDING)
							step = RequestStepStatusEnum.EVL_UNVALUATED_WITH_TIME;
						
					}
					else if(chosenReq.isInExecuation())
					{
						step = RequestStepStatusEnum.EXE_UNEXECUTED_WITH_TIME;
						int days =(int) ( chosenReq.getCurrentStatus().getDueDate().getTime() - chosenReq.getCurrentStatus().getStartDate().getTime() )/(1000*60*60*24);
						chosenReq.setTimeForExecution(days);
					}
					newStatus = new Status(step, RequestMainStatusEnum.OPEN);
					chosenReq.extendTime(newStatus, inspectorApprovalReqPanel.getInspectorExplanation());
					inspectorApprovalReqPanel.removeRow(inspectorApprovalReqPanel.getChosen());
				}
				else if(inspectorApprovalReqPanel.getChooseTab() == ExetendedTab )
				{
					Status newStatus;
					RequestStepStatusEnum step=null;
					Status current = chosenReq.getCurrentStatus().getStatus();
					if(chosenReq.isInEvluation())
					{
						if(current.getsStatus() == RequestStepStatusEnum.EVL_EVLUATION_TIME_EXTENSION_PENDING)
							step = RequestStepStatusEnum.EVL_EVLUATION_EXTENDED;
						else 
							step = RequestStepStatusEnum.EVL_REAVLAUTION_TIME_EXTENSION_EXTENDED;
					}
					else if(chosenReq.isInExecuation())
					{
						step = RequestStepStatusEnum.EXE_UNEXECUTED_EXTENDED;
					}
					else if(chosenReq.isInReviewAndDecision())
					{
						step = RequestStepStatusEnum.REV_REVIEWED_EXTENDED;
					}
					else if(chosenReq.isInTesting())
					{
						step = RequestStepStatusEnum.TST_UTESTED_EXTENDED;
					}
					newStatus = new Status(step, RequestMainStatusEnum.OPEN);
					chosenReq.extendTime(newStatus, inspectorApprovalReqPanel.getInspectorExplanation());
					Worker icm = WorkerManager.getInstance().getICM_MANGER();
					Notificator.sendEmailNotification(icm.getEmail(), "Dear Manager, \n" +
					 		"the request :" + chosenReq.getRequestId() +
			 				" has an additinal time by inspector " + chosenReq.getInspector().getFirstName()+"  "+chosenReq.getInspector().getLastName() +" \n" +
			 				"Have a nice day ICMSYSTEM-AUTOMESSAGE");
					
					inspectorApprovalReqPanel.removeRow(inspectorApprovalReqPanel.getChosen());
				}
				clearFieldsinspectorApprovalReqPanel();
			}
			else if (e.getSource() == inspectorApprovalReqPanel.getBtnDeny())
			{	
				if(inspectorApprovalReqPanel.getChosen()<0)
				{
					JOptionPane.showMessageDialog(new JFrame(),"Please select request from the request list.","Error",JOptionPane.ERROR_MESSAGE);
					return;
				}
				if(inspectorApprovalReqPanel.getChooseTab() == TimeToSepTab )
				{
					Status newStatus;
					RequestStepStatusEnum step=null;
					Status current = chosenReq.getCurrentStatus().getStatus();
					if(chosenReq.isInEvluation())
					{
						if(current.getsStatus() == RequestStepStatusEnum.EVL_UNVALUATED_WITH_TIME_PENDING)
							step = RequestStepStatusEnum.EVL_UNVALUATED_WTIHOUT_TIME;
						else if(current.getsStatus() == RequestStepStatusEnum.EVL_REAVLAUTION_WITH_TIME_PENDING)
							step = RequestStepStatusEnum.EVL_RETURNED_TO_REVALUTION;
					}
					else if(chosenReq.isInExecuation())
					{
						step = RequestStepStatusEnum.EXE_UNEXECUTED_WTIHOUT_TIME;
					}
					newStatus = new Status(step, RequestMainStatusEnum.OPEN);
					chosenReq.denyTimeToStep(newStatus, inspectorApprovalReqPanel.getInspectorExplanation());
					inspectorApprovalReqPanel.removeRow(inspectorApprovalReqPanel.getChosen());
				}
				else if(inspectorApprovalReqPanel.getChooseTab() == ExetendedTab )
				{
					Status newStatus;
					RequestStepStatusEnum step=null;
					Status current = chosenReq.getCurrentStatus().getStatus();
					if(chosenReq.isInEvluation())
					{
						if(current.getsStatus() == RequestStepStatusEnum.EVL_EVLUATION_TIME_EXTENSION_PENDING)
							step = RequestStepStatusEnum.EVL_EVLUATION_EXTENDED_DENY;
						else 
							step = RequestStepStatusEnum.EVL_REAVLAUTION_TIME_EXTENSION_DENIED;
					}
					else if(chosenReq.isInExecuation())
					{
						step = RequestStepStatusEnum.EXE_UNEXECUTED_EXTENDED_DENY;
					}
					else if(chosenReq.isInReviewAndDecision())
					{
						step = RequestStepStatusEnum.REV_REVIEWED_EXTENDED_DENY;
					}
					else if(chosenReq.isInTesting())
					{
						step = RequestStepStatusEnum.TST_UTESTED_EXTENDED_DENY;
					}
					newStatus = new Status(step, RequestMainStatusEnum.OPEN);
					chosenReq.denyTimeExtension(newStatus, inspectorApprovalReqPanel.getInspectorExplanation());
					inspectorApprovalReqPanel.removeRow(inspectorApprovalReqPanel.getChosen());
				}
				clearFieldsinspectorApprovalReqPanel();
				
			}
		}
	}
	
	private void viewReuestsTableListener(ActionEvent e)
	{
		if(viewReuestsTablePanel!=null)
		{
			if (e.getSource() == viewReuestsTablePanel.btnNext)
			{
				if(viewReuestsTablePanel.isChosen())
				{
				
					int i = viewReuestsTablePanel.getChosen();
					Request req;
					int tab = viewReuestsTablePanel.getChooseTab();

					if(tab==closeReqTab)
					{
						chosenReq = requestCloselist.get(i);
					}
					else if(tab==openReqTab)
					{
						chosenReq = requestOpenlist.get(i);
					}
					else if(tab==suspendReqTab)
					{
						chosenReq = requestSuspendedlist.get(i);
					}
		
					viewReuestDataPanel = new ViewReuestDataPanel();
					GlobalData.guiMangaer.switchScreen(viewReuestDataPanel);
					
					viewReuestDataPanel.setDateOfCreation(chosenReq.getDate().toString());
					viewReuestDataPanel.setInfoSystemName(chosenReq.getInfoSystem().getName());
					viewReuestDataPanel.setInitatorName(chosenReq.getInitiator().getFirstName() +" "+ chosenReq.getInitiator().getLastName());
					viewReuestDataPanel.setCurrentState(chosenReq.getCurrentState());
					viewReuestDataPanel.setProposedChangs(chosenReq.getDescription());
					viewReuestDataPanel.setExcuse(chosenReq.getExecuse());
					viewReuestDataPanel.setNote(chosenReq.getNotes());
					
					List<RequestStatusHistory> historyList = chosenReq.getHistory();
					System.out.println(" historyList.size() : " + historyList.size());
					
					//Build table for the History Of the request list.
					tableData =  new String[historyList.size()][historyList.get(0).dataToStringArray().length];
					for(int j=0; j<tableData.length ; j++)
					{
						tableData[j] = historyList.get(j).dataToStringArray();
					}
					columnNames = historyList.get(0).indexStringArray();
					viewReuestDataPanel.buildTabel(columnNames,tableData);
					setListenerToViewDataPanel(viewReuestDataPanel);
					viewReuestDataPanel.getBtnOpenFile().addActionListener(this);
	
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"To Continue you must Choose Reuquest",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
				
			}
			else if (e.getSource() == viewReuestsTablePanel.btnBack)
			{
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == viewReuestsTablePanel.btnRefresh)
			{	
				showAllRequests() ;
			}
			
		}
		if(viewReuestDataPanel != null)
		{
			if (e.getSource() == viewReuestDataPanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(viewReuestsTablePanel);
			}
			else if (e.getSource() == viewReuestDataPanel.btnNext)
			{	
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if(e.getSource() == viewReuestDataPanel.getBtnOpenFile())
			{
				PDFfile file = chosenReq.getFile();
				if(file!=null)
				{
					new PDFDocument(file, "DateFileFromReq" + chosenReq.getRequestId());
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"To This Reuquest There Is Not Data File",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}
	/**
	 * @param e
	 */
	private void approveOrDenyTimeExtensionRequestListener(ActionEvent e) {
		if (TimeExtensionRequestTableListPanel!=null)
		{
		// Time Extension Listeneres //
		if (e.getSource() == TimeExtensionRequestTableListPanel.btnNext)
		{
			
			 aproovedeny =  new ApproveDenyExtenstionGUI();
			GlobalData.guiMangaer.switchScreen(aproovedeny);
			setListenerToInputPanel(aproovedeny);
			aproovedeny.setdata(TimeExtensionRequestTableListPanel.getChosen() + "");
			
		}
		else if (e.getSource() == TimeExtensionRequestTableListPanel.btnBack){
			GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
		}
		else if ((aproovedeny != null) && (e.getSource() == aproovedeny.btnBack)){
			GlobalData.guiMangaer.switchScreen(TimeExtensionRequestTableListPanel);
		}
		}
	}
	/**
	 * @param e
	 */
	private void initTaskListener(ActionEvent e) {
		if (initRequestTableListPanel!=null){
		if (e.getSource() == initRequestTableListPanel.btnNext) 
			{    													 /*Handle next button in init task main panel */
				if(initRequestTableListPanel.isChosen())
				{
					initTaskPanel = new InitTaskPanel();
					
					
					
					SwingWorker worker = new SwingWorker<Void, Void>() {
						@Override
						 public Void doInBackground() 
						 {
							Request reqChosen = requestToInit.get(initRequestTableListPanel.getChosen());
							
							int reqID = reqChosen.getRequestId();
							
							initTaskPanel.getTextFieldInspector().setText(""+reqChosen.getInspector().getId()+") "+reqChosen.getInspector().getFirstName()+" "+reqChosen.getInspector().getLastName());
							initTaskPanel.getTextFieldReviewr().setText(""+reqChosen.getChairman().getId()+") "+reqChosen.getChairman().getFirstName()+" "+reqChosen.getChairman().getLastName());
							ArrayList<Worker> WorkerList = (ArrayList<Worker>) WorkerManager.getInstance().getIEWorkers();
							for (Worker wo : WorkerList){
								initTaskPanel.getComboboxEvluator().addItem(""+wo.getId()+") "+wo.getFirstName()+" "+wo.getLastName());
								initTaskPanel.getComboboxExceution().addItem(""+wo.getId()+") "+wo.getFirstName()+" "+wo.getLastName());
							}
							//InfoSystem info = GenricOperation.getInfoSystem(infoid, conn)
							Worker SuperVisor = reqChosen.getInfoSystem().getSupervisor();
							initTaskPanel.getComboboxEvluator().setSelectedItem(""+SuperVisor.getId()+") "+SuperVisor.getFirstName()+" "+SuperVisor.getLastName());
							return null;
						}
						public void done(){
							GlobalData.guiMangaer.switchScreen(initTaskPanel);
						}};
					worker.execute();
					initTaskPanel.getBtnreturnToDefault().addActionListener(new ActionListener(){

						@Override
						public void actionPerformed(ActionEvent arg0) {
							// TODO Auto-generated method stub
							Request reqChosen = requestToInit.get(initRequestTableListPanel.getChosen());
							Worker SuperVisor = reqChosen.getInfoSystem().getSupervisor();
							initTaskPanel.getComboboxEvluator().setSelectedItem(""+SuperVisor.getId()+") "+SuperVisor.getFirstName()+" "+SuperVisor.getLastName());
						}
						
					});
					
					
					
					
					setListenerToInputPanel(initTaskPanel);
					}
				else
				{
					//user did not choose any request  
					JOptionPane.showMessageDialog(new JFrame(),"You must choose request to continue", "",JOptionPane.DEFAULT_OPTION);
				}
			
			}else if (e.getSource() == initRequestTableListPanel.btnBack){
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
		else if (initTaskPanel!=null){
			if (e.getSource() == initTaskPanel.btnSubnit){
				
				SwingWorker worker = new SwingWorker<Void, Void>() {
					@Override
					 public Void doInBackground() 
					 {
				 Request reqChosen = requestToInit.get(initRequestTableListPanel.getChosen());
				 int reviewer = reqChosen.getChairman().getId();
				 String sid = (String) (initTaskPanel.getComboboxEvluator().getSelectedItem());
				 String[] asid =  sid.split("\\)");
				  System.out.println("OK>?");
				  int EvalId = Integer.parseInt(asid[0]);
				  sid = (String) (initTaskPanel.getComboboxExceution().getSelectedItem());
				  asid =  sid.split("\\)");
				   int ExeId = Integer.parseInt(asid[0]);
				   int  EXMDate=(Integer) initTaskPanel.getComboboxEXM().getSelectedItem();
				   int RvrDate= (Integer) initTaskPanel.getTextFieldRvrDate().getSelectedItem();
				/*   EvalDate =  Integer.parseInt(initTaskPanel.getTextFieldDateEvl().getText());
				   RvrDate =  Integer.parseInt(initTaskPanel.getTextFieldRvrDate().getText());
				  if ( initTaskPanel.getTextFieldDateEvl().getText().isEmpty())
				  {
					  EvalDate=10;
				  }
				  if ( initTaskPanel.getTextFieldRvrDate().getText().isEmpty())
				  {
					  RvrDate=10;
				  }
				  System.out.println(initTaskPanel.getTextFieldDateEvl().getText() + "- ?????"+ RvrDate);
				  if ((RvrDate>7) || (EvalDate>7))
				  {
					  JOptionPane.showMessageDialog(new JFrame(),"Time cannot exceed more than 7 days", "",JOptionPane.DEFAULT_OPTION);
					  return null;
				  }*/
				  HashMap<String,Integer> map = new HashMap<String,Integer>();
				  map.put("ReqID", reqChosen.getRequestId());
				  map.put("RvrID", reviewer);
				  map.put("RvrDate", RvrDate);
				  map.put("EvlId", EvalId);
				  map.put("ExeId", ExeId);
				  map.put("EXMDate", EXMDate);
				  
				 
				  
				  RequestManager.getInstance().InitTask(map);
				  // DateFormat now = DateFormat.getDateInstance();
				return null;
				   
				 //  DateModel<Date> date = (DateModel<Date>) initTaskPanel.getDatePanelImplEva().getModel();
				  // System.out.println(now +" "+date.getDay());
					 }
					public void done(){
						JOptionPane.showMessageDialog(new JFrame(),"Task Was initlized","", JOptionPane.INFORMATION_MESSAGE);
						GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
					}};
				worker.execute();   
			}else if (e.getSource() == initTaskPanel.btnBack){
				GlobalData.guiMangaer.switchScreen(initRequestTableListPanel);
			}
		}
		}
	}
	/**
	 * @param e
	 */
	private void suspendRequestListner(ActionEvent e)
	{
		if (suspendRequestTableListPanel !=null)
		{
			if (e.getSource() == suspendRequestTableListPanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == suspendRequestTableListPanel.btnNext)
			{	
				if(suspendRequestTableListPanel.isChosen())
				{
					suspendRequestPanel = new SuspendRequestPanel();
					GlobalData.guiMangaer.switchScreen(suspendRequestPanel);
					
					int i = suspendRequestTableListPanel.getChosen();
					chosenReq = requestToChoose.get(i);;

					suspendRequestPanel.setDateOfCreation(chosenReq.getDate().toString());
					suspendRequestPanel.setInfoSystemName(chosenReq.getInfoSystem().getName());
					suspendRequestPanel.setInitatorName(chosenReq.getInitiator().getFirstName() +" "+ chosenReq.getInitiator().getLastName());
					suspendRequestPanel.setCurrentState(chosenReq.getCurrentState());
					suspendRequestPanel.setProposedChangs(chosenReq.getDescription());
					suspendRequestPanel.setExcuse(chosenReq.getExecuse());
					suspendRequestPanel.setNote(chosenReq.getNotes());
					List<RequestStatusHistory> historyList = chosenReq.getHistory();
					System.out.println(" historyList.size() : " + historyList.size());
					
					//Build table for the History Of the request list.
					tableData =  new String[historyList.size()][historyList.get(0).dataToStringArray().length];
					for(int j=0; j<tableData.length ; j++)
					{
						tableData[j] = historyList.get(j).dataToStringArray();
					}
					columnNames = historyList.get(0).indexStringArray();
					suspendRequestPanel.buildTabel(columnNames,tableData);
					setListenerToInputPanel(suspendRequestPanel);
					suspendRequestPanel.getBtnOpenFile().addActionListener(this);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"To Continue you must Choose Reuquest",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
			else if (e.getSource() == suspendRequestTableListPanel.btnRefresh)
			{	
				suspendRequest();
			}
		}
        if(suspendRequestPanel!=null)
		{
			if (e.getSource() == suspendRequestPanel.btnBack)
			{	
				System.out.println("suspendRequestPanel.btnBack");
				GlobalData.guiMangaer.switchScreen(suspendRequestTableListPanel);
			}
			else if (e.getSource() == suspendRequestPanel.btnSubnit)
			{	
				if( chosenReq.suspend(1) )
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"The Reuquest Is Now Suspend",
							"",
							JOptionPane.INFORMATION_MESSAGE);
					GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"There is a problem resume the request, try again later.",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
				
			}
			else if(e.getSource() == suspendRequestPanel.getBtnOpenFile())
			{
				PDFfile file = chosenReq.getFile();
				if(file!=null)
				{
					new PDFDocument(file, "DateFileFromReq" + chosenReq.getRequestId());
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"To This Reuquest There Is Not Data File",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
		}
	}
	/**
	 * @param e
	 */
	private void closeRequestListener(ActionEvent e)
	{
		if (closeRequestTableListPanel !=null)
		{
			if (e.getSource() == closeRequestTableListPanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
			}
			else if (e.getSource() == closeRequestTableListPanel.btnNext)
			{	
				if(closeRequestTableListPanel.isChosen())
				{
					closeRequestPanel = new CloseRequestPanel();
					GlobalData.guiMangaer.switchScreen(closeRequestPanel);
					setListenerToInputPanel(closeRequestPanel);
		
					if(closeRequestTableListPanel.isChosen())
					{
						closeRequestPanel = new CloseRequestPanel();
						GlobalData.guiMangaer.switchScreen(closeRequestPanel);
						
						int i = closeRequestTableListPanel.getChosen();
						chosenReq = requestToChoose.get(i);

						closeRequestPanel.setDateOfCreation(chosenReq.getDate().toString());
						closeRequestPanel.setInfoSystemName(chosenReq.getInfoSystem().getName());
						closeRequestPanel.setInitatorName(chosenReq.getInitiator().getFirstName() +" "+ chosenReq.getInitiator().getLastName());
						closeRequestPanel.setCurrentState(chosenReq.getCurrentState());
						closeRequestPanel.setProposedChangs(chosenReq.getDescription());
						closeRequestPanel.setExcuse(chosenReq.getExecuse());
						closeRequestPanel.setNote(chosenReq.getNotes());
						
						List<RequestStatusHistory> historyList = chosenReq.getHistory();
						System.out.println(" historyList.size() : " + historyList.size());
						
						//Build table for the History Of the request list.
						tableData =  new String[historyList.size()][historyList.get(0).dataToStringArray().length];
						for(int j=0; j<tableData.length ; j++)
						{
							tableData[j] = historyList.get(j).dataToStringArray();
						}
						columnNames = historyList.get(0).indexStringArray();
						closeRequestPanel.buildTabel(columnNames,tableData);
						setListenerToInputPanel(closeRequestPanel);
						closeRequestPanel.getBtnOpenFile().addActionListener(this);
					}
					else
					{
						JOptionPane.showMessageDialog(new JFrame(),
								"To Continue you must Choose Reuquest",
								"Error",
								JOptionPane.ERROR_MESSAGE);
					}
					
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),"To Continue you must Choose Request", "",JOptionPane.DEFAULT_OPTION);
				}
				
				//closeRequestPanel.setdata("1234656");
			}
			else if (e.getSource() == closeRequestTableListPanel.btnRefresh)
			{	
				closeRequest();
			}
		}
		if(closeRequestPanel != null)	
		{
			if (e.getSource() == closeRequestPanel.btnBack)
			{	
				GlobalData.guiMangaer.switchScreen(closeRequestTableListPanel);
			}
			else if (e.getSource() == closeRequestPanel.btnSubnit)
			{	
				if( chosenReq.close(1) )
				{
					RequestStepStatusEnum old = chosenReq.getCurrentStatus().getStatus().getsStatus();
					String mailToSend;
					User init = chosenReq.getInitiator();
					if(old == RequestStepStatusEnum.TST_PASSED)
					{
						mailToSend = "Dear " + init.getFirstName() + " " + init.getLastName() + ",\n " + 
								     "Your Requests number " + chosenReq.getRequestId() + " the required change has been made.\n " +
								     "Sincerly yours ICM staff.";
					}
					else // old == RequestStepStatusEnum.REV_REVIEWED_CLOSE)
					{
						mailToSend = "Dear " + init.getFirstName() + " " + init.getLastName() + ",\n " + 
							     "Your Requests number " + chosenReq.getRequestId() + " the required change has been denied.\n " +
							     "Sincerly yours ICM staff.";
					}
					Notificator.sendEmailNotification(chosenReq.getInitiator().getEmail(),mailToSend);
							
			
					JOptionPane.showMessageDialog(new JFrame(),
							"The Reuquest Is Now Close",
							"",
							JOptionPane.INFORMATION_MESSAGE);
					GlobalData.guiMangaer.switchScreen(GlobalData.mainScreen);
				}
				else
				{
					JOptionPane.showMessageDialog(new JFrame(),
							"There is a problem resume the request, try again later.",
							"Error",
							JOptionPane.ERROR_MESSAGE);
				}

			}
		}
	}
	

	
	
	
	
	
	
	
	
	public void assignEvaluator()
	{
		
	}
	public void assignExeLeader()
	{
		
	}
	public int chooseTimeForReview() 
	{
		return 0;
		
	}
	public int chooseTimeForTesting() 
	{
		return 0;
		
	}
	public void approveOrDenyExecutionTime(Request req)
	{
		
		
		
		
		
		
		
		
	}
	public void approveOrDenyEvaluationTime(Request req)
	{
		
	}

	public void approveOrDenyTimeExtensionRequest()
	{
		Request[] requestToClose = RequestManager.getInstance().getAllRequestsWaitingForTimeExtension();
		/*
		 * build the list of what we want to show in the table
		 * String[] columnNames = { "Request Id", "Date of Finish", "status", "Command" };
		 * 
		 */	
		String[] columnNames = { "Request Id", "Date of Finish", "status", "Command" };
		//String[][] tableData = {{}};
		String[][] tableData =  {{"1",     "avi",     "done"    , "11234" },
				{ "15",   "siete",   "done"  , "333333"}};
		
		TimeExtensionRequestTableListPanel = new RequestTableListPanel();	
		GlobalData.guiMangaer.switchScreen(TimeExtensionRequestTableListPanel);
		TimeExtensionRequestTableListPanel.buildTabel(columnNames,tableData);
		setListenerToViewDataPanel(TimeExtensionRequestTableListPanel);	
	}

	public Request[] showAllActiveRequests() 
	{
		return null;
		
	}
	public Request[] showAllFinishedRequests() 
	{
		return null;
		
	}
	public void extendTimeForRequest()
	{
		
	}

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					WorkerRolls x = WorkerRolls.ICM_MANGER;
					System.out.println(x.getText());
					RequestStepStatusEnum y = RequestStepStatusEnum.fromString("2");
					System.out.println(y.getText());
					/*
					GuiManager guiMangaer = new GuiManager();
					GlobalData.guiMangaer = guiMangaer;
					InspectorController v = new InspectorController();
					v.closeRequest();
					*/
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}




}
